#include <iostream>
#include <unistd.h>
#include <pthread.h>

int cnt=0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

struct threadData
{
public:
    threadData(int id)
        :_id(id)
    {}

    int _id;
};

void *handle(void *args)
{
    //分离线程，程序结束自动销毁线程
    pthread_detach(pthread_self());
    //threadData* td=static_cast<threadData*>(args);
    uint64_t id=(uint64_t)args;

    while(true)
    {
        pthread_mutex_lock(&mutex); 
        if(cnt<100)
        {
            pthread_cond_wait(&cond, &mutex); //等待条件变量
            std::cout<<"thread id : "<<id<<" , cnt = "<<cnt++<<std::endl;
            pthread_mutex_unlock(&mutex);
        }
        else 
        {
            pthread_mutex_unlock(&mutex);
            break;
        }     
        usleep(1000);   
    }

    return nullptr;
}

int main()
{
    //创建五个线程并且执行函数
    for(uint64_t i=1;i<=5;i++)
    {
        pthread_t tid;
        //threadData td(i);
        pthread_create(&tid,nullptr,handle,(void*)i);
        usleep(1000);
    }
    
    usleep(1000);

    while(1)
    {
        //pthread_cond_signal(&cond); //唤醒等待队列中的第一个线程
        pthread_cond_broadcast(&cond);
        sleep(1);
    }

    return 0;
}